import { throttle, timeToSec } from '@/lib/util'
import { Base } from './base'

export class NullMedia extends Base {
  protected _currentTime = 0
  protected _playbackRate = 1
  protected _afId = -1
  protected _fps = 30
  constructor() {
    super()
  }

  get currentTime() {
    return this._currentTime
  }

  set currentTime(val: number) {
    this._currentTime = val
    this.emit('timeupdate', this)
  }

  get canplay() {
    return true
  }

  play() {
    this._loop()
    this.emit('playing', this)
  }

  private _loop() {
    cancelAnimationFrame(this._afId)
    this._afId = requestAnimationFrame(() => this._loop())
    this._fakePlay()
  }

  protected get _spf() {
    return 1 / this._fps
  }

  // 应该把定时器放到worker 避免不准确
  private _fakePlay = throttle(
    this._spf * 1e3,
    () => {
      this._currentTime += this._playbackRate * this._spf
      this.emit('timeupdate', this)
    },
    true
  )

  pause() {
    cancelAnimationFrame(this._afId)
    this.emit('pause', this)
  }
}
